<template>
  <!--新增编辑界面-->
  <el-dialog :title="curTitle" width="700px" :visible.sync="editDialog" :close-on-click-modal="false" 
             :modal-append-to-body="false" append-to-body
             :before-close="onClose">
    <el-form
      :model="dataForm"
      label-width="150px"
      :rules="dataFormRules"
      ref="ruleForm"
      size="mini"
      style="text-align: left"
      v-loading="editloading"
    >
      <div class="interview">访视设置</div>
      <el-form-item label="访视编号：" prop="visitNum">
        <el-input
          v-model.trim="dataForm.visitNum"
          auto-complete="off"
          :disabled="readonly"
          style="width: 400px"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="访视名称：" prop="visitName">
        <el-input
          v-model.trim="dataForm.visitName"
          requa
          auto-complete="off"
          :disabled="readonly"
          style="width: 400px"
          maxlength="50"
          show-word-limit
        ></el-input>
      </el-form-item>
      <el-form-item label="访视类型：" style="width: 600px" prop="visitType">
        <el-radio-group v-model="dataForm.visitType" :disabled="readonly">
          <el-radio :label="'1'">公共访视</el-radio>
          <el-radio :label="'2'">非公共访视</el-radio>
          <el-radio :label="'3'">计划外</el-radio>
          <el-radio :label="'4'">循环访视</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="不可见角色：">
        <el-input
          v-model.trim="dataForm.excludeRoles"
          auto-complete="off"
          style="width: 355px"
          :disabled="true"
          :title="dataForm.excludeRoles"
        ></el-input>
        <el-button size="mini" style="width: 40px;margin-left: 5px;" @click="showRoleSelectDialog" v-if="curTitle !== '查看'"
        >...</el-button
        >
      </el-form-item>
      <div class="interview" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">访视窗设置</div>
      <el-form-item label="基线访视：" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-select
          v-model="dataForm.visitWindow.baselineVisitId"
          placeholder="请选择"
          @change="getbaselineTable(false)"
          :disabled="readonly"
          clearable
        >
          <el-option v-for="item in easyList" :key="item.id" :label="item.visitName" :value="item.id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="基线表：" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-select
          v-model="dataForm.visitWindow.baselineTableId"
          placeholder="请选择"
          @change="getbaselineTableDate(false)"
          :disabled="readonly"
          clearable
        >
          <el-option
            v-for="item in baselineList"
            :key="item.id"
            :label="item.tableCode"
            :value="item.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="基线日期：" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-select v-model="dataForm.visitWindow.baselineTime" placeholder="请选择" :disabled="readonly" clearable>
          <el-option
            v-for="item in baselineDateViewList"
            :key="item.fieldKey"
            :label="item.fieldName"
            :value="item.fieldKey"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="间隔：" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-input
          v-model="dataForm.visitWindow.intervalNum"
          auto-complete="off"
          style="width: 100px"
          :disabled="readonly"
        ></el-input>
        <el-select
          v-model="dataForm.visitWindow.intervalType"
          placeholder="请选择"
          style="width: 80px;margin-left:2px"
          :disabled="readonly"
        >
          <el-option label="天" :value="1"></el-option>
          <el-option label="月" :value="2"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Open：" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-input
          v-model="dataForm.visitWindow.openNum"
          auto-complete="off"
          style="width: 100px"
          :disabled="readonly"
        ></el-input>
      </el-form-item>
      <el-form-item label="Close：" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-input
          v-model="dataForm.visitWindow.closeNum"
          auto-complete="off"
          style="width: 100px"
          :disabled="readonly"
        ></el-input>
      </el-form-item>
      <div class="interview" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">随机发药</div>
      <el-form-item label="是否随机：" style="width: 600px" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-radio-group v-model="dataForm.giveMedicine" :disabled="readonly">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="是否发药：" style="width: 600px" v-if="dataForm.visitType == '1' || dataForm.visitType == '2'">
        <el-radio-group v-model="dataForm.randomGiveMedicine" :disabled="readonly">
          <el-radio :label="1">是</el-radio>
          <el-radio :label="2">否</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item v-if="dataForm.visitType == '4'">
        <el-input type="textarea" v-model="dataForm.textarea" style="width: 400px" :disabled="readonly"></el-input>
        <el-button style="margin-left: 20px;" size="mini" @click="settingItem">设定</el-button>
      </el-form-item>
      <el-form-item label="循环访视名称设定：" v-if="dataForm.visitType == '4'">
        注：录入循环访视名称可","字符拼接。或者回车换行，再手工设定。<br />
        例：<br />循环访视1,循环访视2,循环访视3<br />
        或：<br />
        循环访视1<br />
        循环访视2<br />
        循环访视3<br />
        点击设定将自动转换为","字符拼接
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer" v-if="curTitle !== '查看'">
      <el-button size="mini" @click.native="onClose">取消</el-button>
      <el-button size="mini" type="primary" :loading="disabledSubmit" @click.native="submitGeneral">提交</el-button>
    </div>
    <!-- 不可见角色 -->
    <el-dialog width="600px" title="角色配置" :visible.sync="dialogvisic" :close-on-click-modal="false" :modal-append-to-body="false" append-to-body :before-close="isClose">
      <el-button style="float: left; margin-bottom: 10px" size="mini" type="primary" @click="affirmRole">确认</el-button>
      <el-table
        ref="multipleTable"
        :data="RoleList"
        tooltip-effect="dark"
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"> </el-table-column>
        <el-table-column prop="code" label="角色" show-overflow-tooltip> </el-table-column>
        <el-table-column prop="name" label="角色名称" show-overflow-tooltip> </el-table-column>
      </el-table>
    </el-dialog>
  </el-dialog>
  
</template>
<script>
import { mapActions } from 'vuex'

export default {
  props: {
    editDialog: {
      type: Boolean,
      default: () => false
    },
    readonly: {
      type: Boolean,
      default: () => false
    },
    ruForm: {
      type: Object,
      default: () => {}
    },
    curTitle: {
      type: String,
      default: () => ''
    },
    exculdeRoles: {
      type: Array,
      default: () => []
    },
    edcDataBaseId: {
      type: String,
      default: () => ''
    },
    edcBuildProjectId: {
      type: String,
      default: () => ''
    },
    dataBaseVersion: {
      type: String,
      default: () => ''
    },
    environment: {
      type: String,
      default: () => ''
    },
    easyList: {
      type: Array,
      default: () => []
    },
  },
  data() {
    return {
      dataFormRules: {
        visitName: [{ required: true, message: '请输入', trigger: 'blur' }],
        visitNum: [
          { required: true, message: '请输入', trigger: 'blur' },
          { pattern: '[a-zA-Z0-9]', message: '请输入字母或者数字', trigger: 'blur' }],
        visitType: [{ required: true, message: '请选择', trigger: 'blur' }],
      },
      dataForm: {
        textarea: '',
        excludeRoles: '',
        visitName: '',
        visitNum: '',
        visitType: '',
        roleIds: '',
        region: '',
        visitWindow: {
          baselineVisitId: '',
          baselineTableId: '',
          baselineTime: '',
          intervalType: null,
          intervalNum: null,
          openNum: null,
          closeNum: null,
        },
        giveMedicine: 0,
        randomGiveMedicine: 0 
      },
      multipleSelection: [],
      RoleList: [],
      editloading: false,
      dialogvisic: false,
      disabledSubmit: false,
      baselineList: [], // 基线表列表
      baselineDateViewList: [], // 基线表字段列表
    }
  },

  watch: {
    ruForm(val) {
      if (val.id !== '') {
        this.dataForm = { ...val, textarea: val.loopName }
        if (this.dataForm.edcVisitWindow) {
          this.dataForm.visitWindow = this.dataForm.edcVisitWindow
        } else {
          this.dataForm.visitWindow = {}
          this.dataForm.visitWindow.baselineVisitId = ''
          this.dataForm.visitWindow.baselineTableId = ''
          this.dataForm.visitWindow.baselineTime = ''
          this.dataForm.visitWindow.intervalType = ''
          this.dataForm.visitWindow.intervalNum = ''
          this.dataForm.visitWindow.openNum = ''
          this.dataForm.visitWindow.closeNum = ''
        }
      }
    },
  },

  methods: {
    ...mapActions('visitDesign', ['visitCreate', 'visitUpdate', 'roleQuery', 'visitBaselineTable']),
    // 获取edc角色
    edcRole() {
      const params = {
        projectId: this.edcBuildProjectId,
        type: 1,
      }
      this.roleQuery({ params }).then(res => {
        if (res.code === 200) {
          this.RoleList = res.data.records
        }
      })
    },
    // 新增设定按钮
    settingItem() {
      const newarr = this.dataForm.textarea
      this.dataForm.textarea = newarr.split(/[(\r\n)\r\n]+/)
      this.dataForm.textarea = this.dataForm.textarea.join(',')
      console.log(this.dataForm.textarea)
    },
    //  不可见角色多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 不可见角色确认
    affirmRole() {
      const rolsname = []
      for (const val of this.multipleSelection) {
        rolsname.push(val.code)
      }
      this.dataForm.excludeRoles = rolsname.join(',')
      const rols = []
      this.multipleSelection.forEach(item => {
        rols.push(item.code)
      })
      this.roleIds = rols
      this.dialogvisic = false
    },
    // 显示选择角色弹框,在编辑访视时默认勾选已选的角色
    showRoleSelectDialog() {
      this.dialogvisic = true
      this.edcRole()
      this.$nextTick(() => {
        this.multipleSelection = []
        this.$refs.multipleTable.clearSelection()
        if (this.exculdeRoles !== undefined) {
          for (const role of this.exculdeRoles) {
            // 角色列表勾选
            for (const one of this.RoleList) {
              if (role === one.code) {
                this.$refs.multipleTable.toggleRowSelection(one, true)
              }
            }
          }
        }
      })
    },

    /**
     *  获取基线表
     * @param {点击编辑时首次渲染} firstEdit
     * @param {访视窗数据} visitWindow
     */
    getbaselineTable(firstEdit, visitWindow) {
      let baselineVisitId = null
      if (firstEdit) {
        baselineVisitId = visitWindow.visitBaseline != null ? visitWindow.visitBaseline.id : null
      } else {
        baselineVisitId = this.dataForm.visitWindow.baselineVisitId || ''
      }
      if (baselineVisitId == null) {
        this.dataForm.visitWindow.baselineVisitId = ''
        this.dataForm.visitWindow.baselineTableId = ''
        this.editloading = false
        
      }
      const params = {
        visitId: baselineVisitId,
        projectId: this.edcBuildProjectId,
        dataBaseVersion: this.dataBaseVersion,

        environment: this.environment
      }
      this.visitBaselineTable({ params })
        .then(res => {
          if (res.code === 200) {
            this.baselineList = res.data
            // 首次渲染表格取字段列表渲染基线日期列表
            if (firstEdit) {
              this.getbaselineTableDate(firstEdit, visitWindow)
            } else {
              this.dataForm.visitWindow.baselineTableId = ''
              this.dataForm.visitWindow.baselineTime = ''
              this.baselineDateViewList = []
            }
            this.editloading = false
          } else {
            this.editloading = false
            this.$message({
              type: 'info',
              message: '获取失败。原因是：' + res.message,
            })
          }
        })
    },
    /**
     * 获取基线表时间字段
     * @param {点击编辑时首次渲染} firstEdit
     * @param {访视窗数据} visitWindow
     */
    getbaselineTableDate(firstEdit, visitWindow) {
      console.log('firstEdit, visitWindow', firstEdit, visitWindow)
      if (firstEdit) {
        this.dataForm.visitWindow.baselineVisitId = visitWindow.visitBaseline != null ? visitWindow.visitBaseline.id : ''
        this.dataForm.visitWindow.baselineTableId = visitWindow.tableBaseline != null ? visitWindow.tableBaseline.id : ''
        // 首次点击编辑,获取表单时间字段待选项列表，之后再渲染
        for (const form of this.baselineList) {
          if (this.dataForm.visitWindow.baselineTableId === form.id) {
            this.baselineDateViewList = form.fieldList
          }
        }
        this.dataForm.visitWindow.baselineTime = visitWindow.baselineTime
      } else {
        // 手动选择表单后,取时间字段待选项列表,重置时间字段
        this.dataForm.visitWindow.baselineTime = ''
        for (const form of this.baselineList) {
          if (this.dataForm.visitWindow.baselineTableId === form.id) {
            this.baselineDateViewList = form.fieldList
          }
        }
        console.log('baselineDateViewList', this.baselineDateViewList, this.baselineList, this.dataForm.visitWindow)
      }
    },
    onClose () {
      this.$refs.ruleForm.resetFields()
      this.$refs.ruleForm.clearValidate()
      this.dataForm.visitWindow = {}
      this.dataForm.edcVisitWindow = {}
      this.$emit('addVisitCancal')
    },
    isClose() {
      this.dialogvisic = false
    },
    // 提交
    submitGeneral () {
      console.log('121212', this.dataForm, this.ruForm)
      this.disabledSubmit = true
      const validateSuccess = () => {
        const data = {
          databaseId: this.edcDataBaseId,
          databaseVersion: this.dataBaseVersion,
          id: this.dataForm.id,
          visitName: this.dataForm.visitName,
          visitNum: this.dataForm.visitNum,
          visitType: this.dataForm.visitType,
          loopName: this.dataForm.textarea,
          excludeRoleIds: this.roleIds,
          visitWindow: this.dataForm.visitWindow,
          giveMedicine: this.dataForm.giveMedicine,
          randomGiveMedicine: this.dataForm.randomGiveMedicine,
          projectId: this.edcBuildProjectId,
          environment: this.environment,
          sort: this.ruForm.sort
        }
        if (this.curTitle === '编辑') {
          this.visitUpdate({ data })
            .then(resp => {
              if (resp.code === 200) {
                this.$message({
                  type: 'success',
                  message: '编辑成功',
                })
                this.$refs.ruleForm.resetFields()
                this.$refs.ruleForm.clearValidate()
                this.dataForm.visitWindow = {}
                this.$emit('visitOk')
              }
              this.disabledSubmit = false
            })
            .catch(resp => {
              this.disabledSubmit = false
              this.$message({
                type: 'info',
                message: '编辑失败。原因是：' + resp.message,
              })
            })
        } else if (this.curTitle === '新增') {
          this.visitCreate({ data })
            .then(resp => {
              if (resp.code === 200) {
                this.$message({
                  type: 'success',
                  message: '新增成功',
                })
                this.$emit('visitOk')
                this.$nextTick(() => {
                  this.dataForm.visitWindow = {}
                  this.$refs.ruleForm.resetFields()
                  this.$refs.ruleForm.clearValidate()
                })
              }
              this.disabledSubmit = false
            })
            .catch(resp => {
              this.disabledSubmit = false
              this.$message({
                type: 'info',
                message: '新增失败。原因是：' + resp.message,
              })
            })
        }
      }
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          validateSuccess()
        } else {
          this.disabledSubmit = false
          console.log('error submit!!')
          return false
        }
      })
    },
  }
}
</script>
<style lang="scss" scoped>
.interview {
  color: #753cca;
  font-weight: bolder;
  text-align: right;
  font-size: 16px;
  padding-bottom: 10px;
  width: 130px;
}
</style>